﻿using System;
using System.Text.RegularExpressions;
using JetBrains.Annotations;

namespace WikiDoc.Lines
{
    /// <summary>
    /// a CodeStart line
    /// </summary>
    public class CustomSectionLine : WikiLine
    {

        #region 属性

        private string _parserName;
        /// <summary>
        /// Gets the name of the parser.
        /// </summary>
        /// <value>The name of the parser.</value>
        public string ParserName
        {
            get { return _parserName; }
        }


        private string _argv;
        /// <summary>
        /// Gets the argv.
        /// </summary>
        /// <value>The argv.</value>
        public string Argv
        {
            get { return _argv; }
        }

        #endregion


        /// <summary>
        /// 初始化 <see cref="CustomSectionLine"/> 类的新实例.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <param name="parserName">Name of the parser.</param>
        /// <param name="argv">The argv.</param>
        protected CustomSectionLine([NotNull] string line, [CanBeNull] string parserName, [CanBeNull] string argv) : base(line, LineTypes.CustomSection)
        {
            if (line == null) throw new ArgumentNullException("line");

            Line = line;
            _parserName = parserName;
            _argv = argv;
        }

        /// <summary>
        /// 自定义解析器定义： [若干空格][{{{][至少一个空格][解析器名称][至少一个空格][解析器参数]
        /// </summary>
        public static readonly Regex Pattern = new Regex(
            @"\A \s*  \{\{\{  (?:(?: \s+  (\S*) \s* (.*)\z)|(?: \s*\z))",
            RegexOptions.Compiled |
            RegexOptions.CultureInvariant |
            RegexOptions.Singleline |
            RegexOptions.IgnorePatternWhitespace);

        /// <summary>
        /// Tries the parse.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <returns></returns>
        [CanBeNull]
        public static WikiLine TryParse(string line)
        {
            if (line == null) return null;

            var match = Pattern.Match(line);

            return match.Success
                       ? new CustomSectionLine(line,
                                               match.Groups[1].Value,
                                               match.Groups[2].Value)
                       : null;
        }
    }
}
